# import cv2
# import mediapipe as mp
# import numpy as np

# # 初始化 MediaPipe 手部检测模块
# mp_hands = mp.solutions.hands
# hands = mp_hands.Hands(min_detection_confidence=0.7, min_tracking_confidence=0.5)
# mp_drawing = mp.solutions.drawing_utils

# # 打开摄像头
# cap = cv2.VideoCapture(0)
# ret, frame = cap.read()
# black_frame = np.zeros_like(frame)

# Lx_average = 0
# Ly_average = 0
# Rx_average = 0
# Ry_average = 0
# Lcount = 0
# Rcount = 0


# while True:
#     ret, frame = cap.read()
#     if not ret:
#         break

#     rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

#     # 进行手部检测
#     results = hands.process(rgb_frame)

#     # 如果检测到手部
#     if results.multi_hand_landmarks:
#         for landmarks, handedness in zip(results.multi_hand_landmarks, results.multi_handedness):
#             # 绘制手部的关节连接
#             mp_drawing.draw_landmarks(frame, landmarks, mp_hands.HAND_CONNECTIONS)
#             mp_drawing.draw_landmarks(black_frame, landmarks, mp_hands.HAND_CONNECTIONS)

#             x_average = 0
#             y_average = 0
#             count = 0

#             # 获取每个关节点的坐标
#             for id, landmark in enumerate(landmarks.landmark):
#                 h, w, c = frame.shape
#                 cx, cy = int(landmark.x * w), int(landmark.y * h)
#                 cv2.circle(frame, (cx, cy), 5, (0, 255, 0), -1)
#                 cv2.circle(black_frame, (cx, cy), 5, (0, 255, 0), -1)

#                 x_average += cx
#                 y_average += cy
#                 count += 1  # 每次迭代时增加 count

#             # 根据 handedness 确定左右手
#             if handedness.classification[0].label == 'Left':
#                 Lx_average = int(x_average / count)
#                 Ly_average = int(y_average / count)
#                 Lcount += 1
#                 cv2.circle(frame, (Lx_average, Ly_average), 10, (0, 0, 255), -1)
#                 print("Left Hand Position: ", Lx_average, Ly_average)

#             elif handedness.classification[0].label == 'Right':
#                 Rx_average = int(x_average / count)
#                 Ry_average = int(y_average / count)
#                 Rcount += 1
#                 cv2.circle(frame, (Rx_average, Ry_average), 10, (255, 0, 0), -1)
#                 print("Right Hand Position: ", Rx_average, Ry_average)

#     # 显示结果
#     cv2.imshow("Hand Gesture Detection", frame)
#     cv2.imshow("Black Frame", black_frame)

#     # 按 'q' 键退出
#     if cv2.waitKey(1) & 0xFF == ord('q'):
#         break
#     black_frame[:] = 0

# cap.release()
# cv2.destroyAllWindows()



# import cv2
# import mediapipe as mp
# import numpy as np

# # 初始化 MediaPipe 手部检测模块
# mp_hands = mp.solutions.hands
# hands = mp_hands.Hands(min_detection_confidence=0.7, min_tracking_confidence=0.5)
# mp_drawing = mp.solutions.drawing_utils

# # 打开摄像头
# cap = cv2.VideoCapture(0)
# ret, frame = cap.read()
# black_frame = np.zeros_like(frame)

# # 左右手坐标存储数组（每个数组最大存储100个坐标）
# left_hand_positions = []
# right_hand_positions = []

# while True:
#     ret, frame = cap.read()
#     if not ret:
#         break

#     rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

#     # 进行手部检测
#     results = hands.process(rgb_frame)

#     # 如果检测到手部
#     if results.multi_hand_landmarks:
#         for landmarks, handedness in zip(results.multi_hand_landmarks, results.multi_handedness):
#             # 绘制手部的关节连接
#             mp_drawing.draw_landmarks(frame, landmarks, mp_hands.HAND_CONNECTIONS)
#             mp_drawing.draw_landmarks(black_frame, landmarks, mp_hands.HAND_CONNECTIONS)

#             x_average = 0
#             y_average = 0
#             count = 0

#             # 获取每个关节点的坐标
#             for id, landmark in enumerate(landmarks.landmark):
#                 h, w, c = frame.shape
#                 cx, cy = int(landmark.x * w), int(landmark.y * h)
#                 cv2.circle(frame, (cx, cy), 5, (0, 255, 0), -1)
#                 cv2.circle(black_frame, (cx, cy), 5, (0, 255, 0), -1)

#                 x_average += cx
#                 y_average += cy
#                 count += 1  # 每次迭代时增加 count

#             # 根据 handedness 确定左右手
#             if handedness.classification[0].label == 'Left':
#                 Lx_average = int(x_average / count)
#                 Ly_average = int(y_average / count)
#                 left_hand_positions.append((Lx_average, Ly_average))
#                 # 如果数组长度达到100，打印并清空
#                 if len(left_hand_positions) == 100:
#                     print("Left Hand Positions (Last 100): ", left_hand_positions)
#                     left_hand_positions = []  # 清空数组
#                 cv2.circle(frame, (Lx_average, Ly_average), 10, (0, 0, 255), -1)
#                 print("Left Hand Position: ", Lx_average, Ly_average)

#             elif handedness.classification[0].label == 'Right':
#                 Rx_average = int(x_average / count)
#                 Ry_average = int(y_average / count)
#                 right_hand_positions.append((Rx_average, Ry_average))
#                 # 如果数组长度达到100，打印并清空
#                 if len(right_hand_positions) == 100:
#                     print("Right Hand Positions (Last 100): ", right_hand_positions)
#                     right_hand_positions = []  # 清空数组
#                 cv2.circle(frame, (Rx_average, Ry_average), 10, (255, 0, 0), -1)
#                 print("Right Hand Position: ", Rx_average, Ry_average)

#     # 显示结果
#     cv2.imshow("Hand Gesture Detection", frame)
#     cv2.imshow("Black Frame", black_frame)

#     # 按 'q' 键退出
#     if cv2.waitKey(1) & 0xFF == ord('q'):
#         break
#     black_frame[:] = 0

# cap.release()
# cv2.destroyAllWindows()


import cv2
import mediapipe as mp
import numpy as np

# 初始化 MediaPipe 手部检测模块
mp_hands = mp.solutions.hands
hands = mp_hands.Hands(min_detection_confidence=0.85, min_tracking_confidence=0.7)
mp_drawing = mp.solutions.drawing_utils

# 打开摄像头
cap = cv2.VideoCapture(0)

# 获取视频帧
ret, frame = cap.read()
black_frame = np.zeros_like(frame)

# 左右手坐标存储数组（每个数组最大存储100个坐标）
left_hand_positions = []
right_hand_positions = []

# 用于判断是否有明显的来回变换的阈值
movement_threshold_L = 25  # 手的水平/垂直位移超过这个值认为是一次有效的变换
movement_threshold_H = 150
# 用于统计来回变化的次数
left_hand_movement_count = 0
right_hand_movement_count = 0

# 用于记录上一个手的位置
prev_left_hand_pos = None
prev_right_hand_pos = None

# 计数器，每30次分析一次
frame_count = 0

# 循环处理视频帧
while True:
    ret, frame = cap.read()
    if not ret:
        break

    rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    # 进行手部检测
    results = hands.process(rgb_frame)

    # 如果检测到手部
    if results.multi_hand_landmarks:
        for landmarks, handedness in zip(results.multi_hand_landmarks, results.multi_handedness):
            # 绘制手部的关节连接
            mp_drawing.draw_landmarks(frame, landmarks, mp_hands.HAND_CONNECTIONS)
            mp_drawing.draw_landmarks(black_frame, landmarks, mp_hands.HAND_CONNECTIONS)

            x_average = 0
            y_average = 0
            count = 0

            # 获取每个关节点的坐标
            for id, landmark in enumerate(landmarks.landmark):
                h, w, c = frame.shape
                cx, cy = int(landmark.x * w), int(landmark.y * h)
                cv2.circle(frame, (cx, cy), 5, (0, 255, 0), -1)
                cv2.circle(black_frame, (cx, cy), 5, (0, 255, 0), -1)

                x_average += cx
                y_average += cy
                count += 1  # 每次迭代时增加 count

            # 根据 handedness 确定左右手
            if handedness.classification[0].label == 'Left':
                Lx_average = int(x_average / count)
                Ly_average = int(y_average / count)
                left_hand_positions.append((Lx_average, Ly_average))

                # 计算手的位置变化
                if prev_left_hand_pos:
                    lx_prev, ly_prev = prev_left_hand_pos
                    move_distance = np.sqrt((Lx_average - lx_prev)**2 + (Ly_average - ly_prev)**2)
                    if move_distance > movement_threshold_L and move_distance < movement_threshold_H:
                        left_hand_movement_count += 1  # 记录一次有效变换

                # 更新上一个左手位置
                prev_left_hand_pos = (Lx_average, Ly_average)

                # 每30帧进行一次分析
                if frame_count % 15 == 0:
                    print("Left Hand Movement Count (Last 30 frames): ", left_hand_movement_count)
                    left_hand_movement_count = 0  # 重置计数

                cv2.circle(frame, (Lx_average, Ly_average), 10, (0, 0, 255), -1)
                print("Left Hand Position: ", Lx_average, Ly_average)

            elif handedness.classification[0].label == 'Right':
                Rx_average = int(x_average / count)
                Ry_average = int(y_average / count)
                right_hand_positions.append((Rx_average, Ry_average))

                # 计算手的位置变化
                if prev_right_hand_pos:
                    rx_prev, ry_prev = prev_right_hand_pos
                    move_distance = np.sqrt((Rx_average - rx_prev)**2 + (Ry_average - ry_prev)**2)
                    if move_distance > movement_threshold_L and move_distance < movement_threshold_H:
                        right_hand_movement_count += 1  # 记录一次有效变换

                # 更新上一个右手位置
                prev_right_hand_pos = (Rx_average, Ry_average)

                # 每15帧进行一次分析
                if frame_count % 15 == 0:
                    print("Right Hand Movement Count (Last 30 frames): ", right_hand_movement_count)
                    right_hand_movement_count = 0  # 重置计数

                cv2.circle(frame, (Rx_average, Ry_average), 10, (255, 0, 0), -1)
                print("Right Hand Position: ", Rx_average, Ry_average)

    # 判断是否有呼救
    if left_hand_movement_count > 4 or right_hand_movement_count > 4:
        print("Possible emergency detected!")
        # 显示“Help”字样
        cv2.putText(frame, "Help", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)

    # 显示结果
    cv2.imshow("Hand Gesture Detection", frame)
    cv2.imshow("Black Frame", black_frame)

    # 按 'q' 键退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

    # 清空黑色帧
    black_frame[:] = 0
    frame_count += 1  # 增加帧计数

# 释放资源
cap.release()
cv2.destroyAllWindows()


